package org.eclipsercp.hyperbola.views;

import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.ViewPart;
import org.eclipsercp.hyperbola.model.Contact;
import org.eclipsercp.hyperbola.model.ContactAdapater;
import org.eclipsercp.hyperbola.model.ContactEntry;
import org.eclipsercp.hyperbola.model.ContactGroup;
import org.eclipsercp.hyperbola.model.Session;

public class ContactView extends ViewPart {
	public ContactView() {
	}

	public static final String ID = "org.eclipsercp.hyperbola.views.ContactView";
	private Session session;
	private TreeViewer tvContact;
	private IAdapterFactory contactAdapterFactory = new ContactApdaperFactory();

	@Override
	public void createPartControl(Composite parent) {
		initSession();

		tvContact = new TreeViewer(parent, SWT.MULTI | SWT.V_SCROLL);
		tvContact.setAutoExpandLevel(3);
		Platform.getAdapterManager().registerAdapters(contactAdapterFactory,
				Contact.class);
		getSite().setSelectionProvider(tvContact);
		tvContact.setLabelProvider(new WorkbenchLabelProvider());
		tvContact.setContentProvider(new BaseWorkbenchContentProvider());
		tvContact.setInput(session.getRoot());
		session.getRoot().addContactListener(new ContactAdapater() {
			public void contactChanged(ContactGroup group, Contact entry) {
				tvContact.refresh();
			}
		});
	}

	private void initSession() {
		session = new Session();
		ContactGroup root = session.getRoot();

		ContactGroup friendsGroup = new ContactGroup(root, "Friends");
		friendsGroup.addEntry(new ContactEntry(friendsGroup, "Alize", "aliz",
				"localhost"));
		friendsGroup.addEntry(new ContactEntry(friendsGroup, "Jing Guo",
				"Jing GeGe", "localhost"));

		root.addEntry(friendsGroup);

		ContactGroup otherGroup = new ContactGroup(root, "Other");
		otherGroup.addEntry(new ContactEntry(otherGroup, "Huang YaoShi",
				"TaoHua island", "localhost"));
		root.addEntry(otherGroup);

	}

	@Override
	public void setFocus() {
		tvContact.getControl().setFocus();
	}

	@Override
	public void dispose() {
		Platform.getAdapterManager().unregisterAdapters(contactAdapterFactory,
				Contact.class);
		super.dispose();
	}
}
